package cn.imokay.juc.captainSynchronized;

/**
 * 类锁 static形式
 */
public class ClassStaticLock2 implements Runnable{
    static ClassStaticLock2 instance1 = new ClassStaticLock2();
    static ClassStaticLock2 instance2 = new ClassStaticLock2();

    public void run() {
        try {
            method();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 当没有static时，两个Runnable对象开启线程时，this不同，锁对象不同，相当于没锁
     * 当有static时，锁对象变成了ClassStaticLock.class,类对象只有一个，所以有锁
     * @throws InterruptedException
     */
    private static synchronized void method() throws InterruptedException {
        Thread.sleep(3000);
        System.out.println(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getName() + "结束");

    }

    public static void main(String[] args) {
        Thread t1 = new Thread(instance1);
        Thread t2 = new Thread(instance2);
        t1.start();
        t2.start();

        while (t1.isAlive() || t2.isAlive()) {

        }
        System.out.println("finish");
    }
}
